<template>
	<div class='tinymce'>
		<page-title>编辑文章</page-title>
		<b-container fluid>
			<b-row>
				<b-col cols="9">
					<commons-alert :class="{'success-alert': alert.variant === 'success'}" @alert-dismissed="alertDismissed" :variant="alert.variant"
					 :dismissCountDown="alert.dismissCountDown">{{alert.message}}</commons-alert>
					<div class="mb-2">
						<b-input v-model="title" placeholder="请输入标题"></b-input>
					</div>
					<editor id='tinymce' v-model='tinymceHtml' :init='init'></editor>
				</b-col>
				<b-col cols="3">
					<b-tabs card>
						<b-tab title="上传图片" active>
							<file-upload :accept="upload.accept" :closeable="upload.closeable" :showProgressUnderUploadArea="upload.showProgressAtUnder"
							 :showProgressInUploadArea="!upload.showProgressAtUnder">
								<template v-slot:before-under-area>
									<div class="text-center">可直接拖动下方图片到左边编辑器</div>
								</template>
							</file-upload>
						</b-tab>
						<b-tab title="媒体库">
							<simple-medias></simple-medias>
						</b-tab>
						<b-tab title="标签">
							<simple-tags ref="simpleTagsObj" :initTags="initTags"></simple-tags>
						</b-tab>
						<b-tab title="目录">
							<simple-catalogs ref="simpleCatalogsObj" @catalog-selected="catalogSelected"></simple-catalogs>
						</b-tab>
					</b-tabs>
				</b-col>
			</b-row>
		</b-container>
	</div>
</template>

<script>
	import axios from 'axios'
	import gl from '../commons/global_variable.js'
	import CommonsAlert from '../commons/Alert.vue'
	import PageTitle from '../commons/ContentPageTitle.vue'
	import tinymce from 'tinymce/tinymce'
	import Editor from '@tinymce/tinymce-vue'
	import FileUpload from '../commons/FileUpload.vue'
	import SimpleMedias from './parts/SimpleMedias.vue'
	import SimpleTags from './parts/SimpleTags.vue'
	import SimpleCatalogs from './parts/SimpleCatalogs.vue'
	import EventBus from './ArticleHelper.js'
	import 'tinymce/themes/silver'
	import 'tinymce/icons/default'
	import 'tinymce/plugins/codesample'
	import 'tinymce/plugins/advlist'
	import 'tinymce/plugins/lists'
	import 'tinymce/plugins/table'
	import 'tinymce/plugins/anchor'
	import 'tinymce/plugins/link'
	import 'tinymce/plugins/autolink'
	import 'tinymce/plugins/autosave'
	import 'tinymce/plugins/emoticons'
	import 'tinymce/plugins/emoticons/js/emojis'
	import 'tinymce/plugins/fullpage'
	import 'tinymce/plugins/fullscreen'
	import 'tinymce/plugins/hr'
	import 'tinymce/plugins/image'
	import 'tinymce/plugins/importcss'
	import 'tinymce/plugins/media'
	import 'tinymce/plugins/paste'
	import 'tinymce/plugins/preview'
	import 'tinymce/plugins/print'
	import 'tinymce/plugins/quickbars'
	import 'tinymce/plugins/searchreplace'
	import 'tinymce/plugins/template'
	import 'tinymce/plugins/visualblocks'
	import 'tinymce/plugins/wordcount'


	export default {
		name: "NewArticle",
		created: function() {
			this.$store.commit('menuFoucsOpr', 'new-articles')
			var that = this
			EventBus.$on('save-to-server', function() {
				that.saveToServer()
			})
			if(this.$route.params.id){
				this.loadDetail(this.$route.params.id)
			}
		},
		components: {
			Editor,
			PageTitle,
			FileUpload,
			SimpleMedias,
			SimpleTags,
			SimpleCatalogs,
			CommonsAlert
		},
		data: function() {
			return {
				upload: {
					closeable: false,
					showProgressAtUnder: true,
					accept: "image/*"
				},
				alert: {
					message: '',
					variant: 'warning',
					dismissCountDown: 0
				},
				id: -1,
				title: '',
				tinymceHtml: '',
				catalogIds: [],
				initCatalogIds: [],
				initTags: [],
				init: {
					language_url: '/tinymce/zh_CN.js',
					language: 'zh_CN',
					skin_url: '/tinymce/skins/ui/oxide',
					content_css: '/tinymce/skins/content/default/content.css',
					height: 800,
					branding: false,
					plugins: 'codesample advlist lists table anchor link autolink autosave emoticons fullpage fullscreen' +
						' hr image importcss media paste preview print quickbars searchreplace template visualblocks wordcount ',
					advlist_number_styles: 'default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman',
					lists_indent_on_tab: true,
					default_link_target: '_blank',
					paste_data_images: true,
					templates: [
						{
							title: '模板A',
							description: '就是模板A',
							url: 'templates/templ_1.html'
						},
						{
							title: '模板B',
							description: '就是模板B',
							url: 'templates/templ_2.html'
						}
					],
					template_cdate_classes: 'cdate creationdate',
					template_cdate_format: '%Y-%m-%d %H:%M:%S',
					template_mdate_classes: 'mdate modifieddate',
					template_mdate_format: '%Y-%m-%d %H:%M:%S',
					toolbar: 'MySaveBtn | undo redo searchreplace paste preview print visualblocks ' +
						'| template formatselect | bold italic forecolor backcolor ' +
						'| alignleft aligncenter alignright alignjustify ' +
						'| numlist bullist outdent indent | codesample emoticons hr | image media ' +
						'| table tabledelete tableprops tablerowprops tablecellprops ' +
						'| link ' +
						'| anchor wordcount fullpage fullscreen',
					setup: function(editor) {
						editor.ui.registry.addButton("MySaveBtn", {
							text: '保存',
							icon: 'save',
							tooltip: '保存文章内容到服务器',
							onAction: function() {
								EventBus.$emit("save-to-server")
							}
						})
					}
				}
			}
		},
		methods: {
			loadDetail: function(articleId){
				var that = this
				axios.get(gl.cms_args.server_url + 'article/detail?id=' + articleId).then(function(response){
					var res = response.data
					if(res.code === gl.cms_args.success){
						var articleDto = res.data
						that.id = articleDto.articleId
						that.title = articleDto.title
						that.tinymceHtml = articleDto.content
						that.initCatalogIds = articleDto.catalogs.map(function(it){
							return it.id
						})
						that.initTags = articleDto.tags.map(function(it){
							return {
								value: it.id,
								text: it.name
							}
						})
						that.$refs.simpleCatalogsObj.selectCatalogs(that.initCatalogIds)
					}else{
						that.onQueryError()
					}
				}).catch(function(error){
					that.onQueryError()
				})
			},
			catalogSelected: function(catalogs) {
				this.catalogIds = catalogs.map(function(catalog) {
					return catalog.id
				})
			},
			saveToServer: function() {
				if (this.title === null || this.title.trim().length === 0) {
					this.onSaveError('标题不能为空')
					return
				}
				var tagIds = this.$refs.simpleTagsObj ? this.$refs.simpleTagsObj.getTagIds() : []
				var that = this
				axios.post(gl.cms_args.server_url + 'article/save', {
					id: this.id,
					title: this.title,
					content: this.tinymceHtml,
					tagIds: tagIds,
					catalogIds: this.catalogIds
				}).then(function(response) {
					var res = response.data
					if (res.code === gl.cms_args.success) {
						that.onSaveSuccess()
					} else {
						that.onSaveError('文章保存失败')
					}
				}).catch(function(error) {
					that.onSaveError('文章保存失败')
				})
			},
			onSaveSuccess: function(){
				this.alert.message = '保存成功'
				this.alert.dismissCountDown = 3
				this.alert.variant = 'success'
			},
			onSaveError: function(message) {
				this.alert.message = message
				this.alert.dismissCountDown = 3
				this.alert.variant = 'warning'
			},
			onQueryError: function(){
				this.alert.message = '加载文章数据失败'
				this.alert.dismissCountDown = 3
				this.alert.variant = 'warning'
			},
			alertDismissed: function() {
				this.alert.dismissCountDown = 0
			}
		}
	}
</script>

<style>
	.success-alert {
		width: 50rem;
		margin-left: -25rem;
		position: absolute;
		z-index: 1000;
		left: 25rem;
	}
</style>
